package cat.joronya.supermanager.home;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Locale;

import org.apache.commons.lang3.StringUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.SupermanagerPreferenceActivity;
import cat.joronya.supermanager.home.HomeFragment.OnAboutListener;
import cat.joronya.supermanager.service.SupermanagerServiceHelper;
import cat.joronya.supermanager.widget.CheckableRelativeLayout;

/**
 * Fragment per llistat dels proxims partits.
 * @author pol
 */
public class NextMatchesListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>
{
	// loader id
	private static final int LIST_LOADER = 0x01;
	
	// the adapter
	private NextMatchesAdapter adapter;
	
	private SimpleDateFormat simpleDateFormat = null;
	
	private OnAboutListener mAboutListener;
	
	private String mDay;
	
	/**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = Supermanager.NextMatches.PROJECTION;
    
    public void setDay(String day)
    {
    	mDay = day;
    }
    
    public static NextMatchesListFragment newInstance(String day)
    {
    	NextMatchesListFragment frag = new NextMatchesListFragment();
    	frag.setDay(day);
    	return frag;
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mAboutListener = (OnAboutListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnAboutListener");
        }
    }
    
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) 
	{
    	View view = inflater.inflate(R.layout.next_matches_list, null);
    	
    	simpleDateFormat = new SimpleDateFormat("EEEE d/M/yyyy, HH:mm'h'", Locale.getDefault());
    	
        // Used to map notes entries from the database to views
        adapter = new NextMatchesAdapter(getActivity().getApplicationContext(), null);
        setListAdapter(adapter);
        
        // initialize the loader
        getLoaderManager().initLoader(LIST_LOADER, null, this);
        
        // avisem q el fragment te menu pq es cridi
        setHasOptionsMenu(true);
        
		return view;
	}
    
    @Override
	public void onViewCreated(View view, Bundle savedInstanceState) 
    {
		super.onViewCreated(view, savedInstanceState);
	}

    class NextMatchesAdapter extends CursorAdapter implements CheckableRelativeLayout.OnCheckedChangeListener
	{
    	public NextMatchesAdapter(Context theContext, Cursor theCursor) 
		{
			super(theContext, theCursor, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) 
		{
			// row type
			int type = cursor.getInt(1);
			if( type == 0 )
				bindHeaderView(view, context, cursor);
			else
				bindRowView(view, context, cursor);
		}
		
		public void bindHeaderView(View view, Context context, Cursor cursor) 
		{
			// background del header gris
			view.setBackgroundColor(getResources().getColor(R.color.dark_grey));
			
			// mostrem row header i ocultem l'altre
			View headerRow = view.findViewById(R.id.next_matches_list_header_row);
			headerRow.setVisibility(View.VISIBLE);
			View normalRow = view.findViewById(R.id.next_matches_list_normal_row);
			normalRow.setVisibility(View.GONE);
			
			int day = cursor.getInt(2);
			String competition = cursor.getString(3);
			
			TextView headerView = (TextView)view.findViewById(R.id.next_matches_list_row_name);
			headerView.setText(getString(R.string.next_matches_list_header_row, competition, day+""));
		}
		
		public void bindRowView(View view, Context context, Cursor cursor) 
		{
			// background de la row normal blanc
			view.setBackgroundColor(getResources().getColor(R.color.white));
						
			// mostrem row normal i ocultem l'altre
			View headerRow = view.findViewById(R.id.next_matches_list_header_row);
			headerRow.setVisibility(View.GONE);
			View normalRow = view.findViewById(R.id.next_matches_list_normal_row);
			normalRow.setVisibility(View.VISIBLE);

			String homeTeam = cursor.getString(4);
			String vsTeam = cursor.getString(6);
			long timestamp = cursor.getInt(8);
			Timestamp matchDateTimestamp = new Timestamp(timestamp*1000);
			String matchDateString = simpleDateFormat.format(matchDateTimestamp.getTime());
			String retransmissions = cursor.getString(9);
			
			TextView teamsView = (TextView)view.findViewById(R.id.next_matches_list_row_teams);
			teamsView.setText(homeTeam+" - "+vsTeam);
			
			TextView dateView = (TextView)view.findViewById(R.id.next_matches_row_date);
			dateView.setText(StringUtils.capitalize(matchDateString));
			
			TextView retransmissionsView = (TextView)view.findViewById(R.id.next_matches_row_transmissions);
			retransmissionsView.setText(retransmissions);
		}
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) 
		{
			// create the new view
			LayoutInflater inflater = LayoutInflater.from(context);
			
			CheckableRelativeLayout row = (CheckableRelativeLayout)inflater.inflate(R.layout.next_matches_list_row, parent, false);
			row.setOnCheckedChangeListener(this);
			return row;
		}

		public void onCheckedChanged(CheckableRelativeLayout layout,
				boolean isChecked) {
			layout.setBackgroundColor((isChecked)? 
					getResources().getColor(R.color.blue):getResources().getColor(R.color.white));
		}
    }

    /**
	 * Al clicar una lliga privada anem al detall.
	 */
    @Override
	public void onListItemClick(ListView l, View v, int position, long id)
	{
		Log.d(Supermanager.TAG,"veient detall de lliga privada amb _id: "+id);
	}
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) 
    {
    	inflater.inflate(R.menu.home, menu);
    	super.onCreateOptionsMenu(menu, inflater);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
    	// Handle item selection
        switch (item.getItemId()) 
        {
        	case R.id.refresh:
				// cridar refresh al REST method
           		SupermanagerServiceHelper.getInstance(getActivity()).fullUpdate(null,true);
				return true;
        	case R.id.settings:
        		// llancem Preferences activity
        		Intent settingsActivity = new Intent(getActivity(),
        				SupermanagerPreferenceActivity.class);
        		startActivity(settingsActivity);
        		return true;
        	case R.id.about:
        		// show about progress
        		mAboutListener.showAboutDialog();
        		return true;
        	default:
        		return super.onOptionsItemSelected(item);
        }
    }
    
    public Loader<Cursor> onCreateLoader(int id, Bundle bundle) 
	{
    	// append the day, to show next days from actual
    	Uri uri = Supermanager.NextMatches.CONTENT_URI;
    	uri = Uri.withAppendedPath(uri, mDay);
    	
		CursorLoader cursorLoader = new CursorLoader(getActivity(),
				uri, 
				PROJECTION, 
				null, 
				null, 
				Supermanager.NextMatches.DEFAULT_SORT_ORDER);
	    return cursorLoader;
	}

	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) 
	{
		adapter.swapCursor(cursor);
	}

	public void onLoaderReset(Loader<Cursor> loader) 
	{
		adapter.swapCursor(null);
	}
    
    
}
